import javax.sound.sampled.*;
import java.io.IOException;

public class SoundRecorder implements Runnable{
    private AudioFormat m_format;
    private int m_bufferSize;
    private AudioInputStream m_soundStream;
    private TargetDataLine m_recordSoundLine;
    private Thread m_thread;
    private MessageQueue m_messageQueue;

    public SoundRecorder(AudioFormat format, int bufferSize, MessageQueue messageQueue)
    {
        m_format = format;
        m_bufferSize = bufferSize;
        m_messageQueue = messageQueue;

        DataLine.Info info = new DataLine.Info(TargetDataLine.class, m_format);
        if (!AudioSystem.isLineSupported(info))
        {
            System.out.println("Line not supported " + info);
            return;
        }

        try
        {
            m_recordSoundLine = (TargetDataLine)AudioSystem.getLine(info);
            m_recordSoundLine.open(m_format, m_recordSoundLine.getBufferSize());
        }
        catch (LineUnavailableException e)
        {
            System.out.println("Line unavailable " + e);
            return;
        }
        m_soundStream = new AudioInputStream(m_recordSoundLine);
        m_thread = new Thread(this);
    }

    public void setDaemon(boolean isDaemon)
    {
        m_thread.setDaemon(isDaemon);
    }
    
    public void start()
    {
        m_thread.start();
    }

    public void run()
    {
        byte[] soundData = new byte[m_bufferSize];
        int byteCount;

        m_recordSoundLine.start();
        while (true)
        {
            try
            {
                byteCount = m_soundStream.read(soundData, 0, soundData.length);
                m_messageQueue.push(new Message(Message.SOUND, soundData, byteCount));
                //System.out.println("read " + byteCount);
                //System.out.println("read queue " + m_messageQueue.queue.size());
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }

    public void stop()
    {
        m_thread.interrupt();
        m_recordSoundLine.close();
    }
    
    
}
